package com.mvd.app.upload;

import android.annotation.TargetApi;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.iceteck.silicompressorr.SiliCompressor;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.application.UploadEvent;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.VideoUploadModel;
import com.vincent.videocompressor.VideoCompress;
import com.zolad.videoslimmer.VideoSlimmer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ProjectName: PDA_38900_guizhou
 * @Package: com.mvd.app.upload
 * @ClassName: MyUploadService
 * @Description: java类作用描述
 * @Author: liuxj
 * @CreateDate: 2020-11-02 15:42
 * @UpdateUser: 更新者
 * @UpdateDate: 2020-11-02 15:42
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class MyUploadService extends Service implements ApiConfig {
    private String outputDir =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    private long startTime, endTime;


    //    private Compressor mCompressor;
    private String currentOutputVideoPath = "";//压缩后的视频地址

    private String videoTime = "";//获取视频时长
    private int videoWidth = 0;//获取视频的宽度
    private int videoHeight = 0;//获取视频的高度
    private int videoGotation = 0;//获取视频的角度
    private Bitmap mBitMap;
    private Double videoLength = 0.00;//视频时长 s
    private Handler handler = new Handler();
    MyRunnable myRunnable = new MyRunnable();//定义MyRunnable的对象；
    VideoUploadModel model = null;
//    private CustomProgressDialog mProcessingDialog;

//    private String mVideoPath = "";//原视频地址

    //    public static final String PATH =
//            Environment.getExternalStorageDirectory().getAbsolutePath() + "/apeng/";
    class MyRunnable implements Runnable {//内部类实现Runnable接口；

        @Override
        public void run() {//还是在Runnable重写的run()方法中更新界面；
//            text.setText("使用Handler更新了界面");
//            videoCompress(model.getSize(), model.getZp(), model);
//            video_VideoProcessor(model.getSize(), model.getZp(), model);
//            videoCompress_low(model.getSize(), model.getZp(), model);
//            videoCompress_medium(model.getSize(), model.getZp(), model);
            siliCompressor(model.getSize(), model.getZp(), model);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        UtilsLog.e("MyService.onBind------------");
        return null;
    }

    @Override
    public void onCreate() {
        UtilsLog.e("MyService.onCreate------------");
        EventBus.getDefault().register(this);
        super.onCreate();
//        initFile();
//        initVideo();
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void getUploadEventBus(UploadEvent event) {
        UtilsLog.e("MyUploadService===" + event.getMessage());
        UtilsLog.e("MyUploadService===" + event.getPath());

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        UtilsLog.e("MyService.onStartCommand------------");
        if (intent != null) {
//            String data=intent.getStringExtra("service_data");
//            UserAccountModel model= (UserAccountModel) intent.getSerializableExtra("service_user_model");
//            UtilsLog.e("MyService.onStartCommand--------data----"+data);
//            UtilsLog.e("MyService.onStartCommand--------UserAccountModel----"+model.toString());
            model = (VideoUploadModel) intent.getSerializableExtra("service_model");
            UtilsLog.e("MyService.onStartCommand--------VideoUploadModel----" + model.toString());

//            videoCompress(model.getSize(), model.getZp(), model);

            String quality = SharedPreferencesUtils.getVideoQuality(this);
            UtilsLog.e("MyUploadService---视频画质==" + quality);
            String logStrqw = "\n" + "MyUploadService---外检上传视频--onStartCommand--" +
                    "\n" + "carsInforModel:" + model.toString() + "\n"
                    + "SharedPreferencesUtils.getDongBeiVersion(this):" + SharedPreferencesUtils.getDongBeiVersion(this) + "\n";
            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());

            if (SharedPreferencesUtils.getDongBeiVersion(this)) {
                new Thread() {

                    @Override
                    public void run() {
                        handler.post(myRunnable);//调用Handler.post方法；
                    }
                }.start();
//                video_VideoProcessor(model.getSize(), model.getZp(), model);
            } else {
                videoCompress_no(model);
            }
//            if (quality.equals("低")) {
//                videoCompress_low(model.getSize(), model.getZp(), model);
//            } else if (quality.equals("中")) {
//                videoCompress_medium(model.getSize(), model.getZp(), model);
//            } else if (quality.equals("高")) {
//                videoCompress_high(model.getSize(), model.getZp(), model);
//            } else if (quality.equals("无")) {
//                videoCompress_no(model);
////                videoCompress(model.getSize(), model.getZp(), model);
//            } else {
////                startCompress(model);
//            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        UtilsLog.e("MyService.onDestroy------------");
        super.onDestroy();
//        if (mCompressor != null) {
//            mCompressor.destory();
//        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        UtilsLog.e("MyService.onUnbind------------");
        EventBus.getDefault().unregister(this);
        return super.onUnbind(intent);
    }

//    void video_VideoProcessor(String videoUriString, String videoPath, final VideoUploadModel model) {
//        UtilsLog.e("video_VideoProcessor===videoUriString==" + videoUriString);
//        UtilsLog.e("video_VideoProcessor===videoPath==" + videoPath);
//        try {
//            VideoProcessor.processor(this)
//                    .input(videoUriString)
//                    .output(videoPath)
//                    .outWidth(800)
//                    .outHeight(800)
//                    .progressListener(new VideoProgressListener() {
//                        @Override
//                        public void onProgress(float progress) {
//                            UtilsLog.e("video_VideoProcessor===progress==" + progress);
//                        }
//                    })
//                    .process();
//        } catch (Exception e) {
//            UtilsLog.e("video_VideoProcessor===" + e);
//            UtilsLog.e("video_VideoProcessor===" + e.toString());
//            e.printStackTrace();
//        }
//    }

    void videoCompress(String videoUriString, String videoPath, final VideoUploadModel model) {
//               VideoSlimmer.convertVideo(videoUriString, videoPath, 480, 480, 200 * 360 * 30, new VideoSlimmer.ProgressListener() {
        String logStrqw = "\n" + "MyUploadService---外检上传视频--videoCompress--" +
                "\n" + "carsInforModel:" + model.toString() + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());

        VideoSlimmer.convertVideo(videoUriString, videoPath, 800, 800, 200 * 360 * 30, new VideoSlimmer.ProgressListener() {
            @Override
            public void onStart() {
                UtilsLog.e("videoCompress---视频路径=onStart=");
            }

            @Override
            public void onFinish(boolean result) {
                UtilsLog.e("videoCompress---视频路径=onFinish=" + result);
//                //convert finish,result(true is success,false is fail)
                String logStrqw = "\n" + "MyUploadService---外检上传视频--videoCompress--onFinish--" +
                        "\n" + "result:" + result + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
                if (result) {
                    getDataUploadVideo(model, true, "");
                }
            }

            @Override
            public void onProgress(float percent) {
                UtilsLog.e("videoCompress---视频路径=onProgress=" + percent);
                String logStrqw = "\n" + "MyUploadService---外检上传视频--videoCompress--onProgress--" +
                        "\n" + "percent:" + String.valueOf(percent) + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
            }
        });
    }

    class VideoCompressAsyncTask extends AsyncTask<String, String, String> {

        Context mContext;

        public VideoCompressAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... paths) {
            String filePath = null;
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(paths[0]);
                String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
                String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
                double widths = Integer.parseInt(width) * 0.9;
                double heights = Integer.parseInt(height) * 0.9;
                int videoWidth = new Double(widths).intValue();
                int videoHeight = new Double(heights).intValue();
                filePath = SiliCompressor.with(mContext).compressVideo(paths[0], paths[1],videoHeight,videoWidth,1200000);
                Log.e("tag", "压缩完成了老哥，要开始上传啦~~");
                Log.e("tag","压缩后的路径为==="+ filePath);
                if (filePath != null){
                    String logStr = "视频压缩完成，即将开始上传=======";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                    getDataUploadVideo2(model, filePath, "");
                }else {
                    String logStr = "视频压缩失败=======";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            return filePath;

        }

        //得到压缩好的路径
        @Override
        protected void onPostExecute(String compressedFilePath) {
            super.onPostExecute(compressedFilePath);

        }
    }
    void siliCompressor (String videoUriString, String videoPath, final VideoUploadModel model){
        String foder = Environment.getExternalStorageDirectory() + "/compress/";
        Log.e("tag","压缩视频的文件夹为："+ foder);
        File file = new File(foder);
        if (!file.exists()) {
            file.mkdirs();
        }
        new VideoCompressAsyncTask(this).execute(videoUriString, file.getPath());
//        StringfilePath= SiliCompressor.with(BaseApplication.getSelf()).compressVideo(videoPath, destinationDirectory，outWidth，outHeight，bitrate);参数传入原视频videoPath和压缩后destinationDirectory存放的文件夹，返回压缩后图片绝对路径。横屏视频的outWidth宽度   outHeight高度   bitrate比特率（码率）越高数据大  体积越大一般450000
    }
    void videoCompress_medium(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";

        VideoCompress.compressVideoMedium(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    void videoCompress_high(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoHigh(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    void videoCompress_no(VideoUploadModel model) {
        getDataUploadVideo(model, false, "");
    }

    void videoCompress_low(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoLow(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频上传进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    private Locale getLocale() {
        Configuration config = getResources().getConfiguration();
        Locale sysLocale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sysLocale = getSystemLocale(config);
        } else {
            sysLocale = getSystemLocaleLegacy(config);
        }

        return sysLocale;
    }

    @SuppressWarnings("deprecation")
    public static Locale getSystemLocaleLegacy(Configuration config) {
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Configuration config) {
        return config.getLocales().get(0);
    }

    int upload_times = 0;//上传视频的次数

    //上传视频 is:是否压缩  true  是   false 否
    private void getDataUploadVideo(final VideoUploadModel carsInforModel, boolean is, String currentOutputVideoPath) {
        String video_url_path = "";
        if (!TextUtils.isEmpty(currentOutputVideoPath)) {
            video_url_path = currentOutputVideoPath;
        } else {
            if (is) {
                video_url_path = carsInforModel.getZp();
            } else {
                video_url_path = carsInforModel.getSize();
            }
        }
        UtilsLog.e("MyUploadService---getDataUploadVideo==start==" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
        UtilsLog.e("MyUploadService---上传视频---currentOutputVideoPath==" + currentOutputVideoPath);
        UtilsLog.e("MyUploadService---上传视频---carsInforModel==" + carsInforModel.toString());
        UtilsLog.e("MyUploadService---上传视频---url==" + carsInforModel.getPath());
        String logStrqw = "\n" + "MyUploadService---外检上传视频--getDataUploadVideo--" +
                "\n" + "currentOutputVideoPath::" + currentOutputVideoPath + "\n"
                + "carsInforModel:" + carsInforModel.toString() + "\n"
                + "url:" + carsInforModel.getPath() + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
        OkGo.<String>post(carsInforModel.getPath())
//                .isMultipart(true)
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", carsInforModel.getVideoType())
                .params("ItemCode", carsInforModel.getItemCode())
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getCarNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", carsInforModel.getLine())
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", new File(video_url_path))
                //开始时间
                .params("StartTime", carsInforModel.getStartTime())
                //结束时间
                .params("EndTime", carsInforModel.getEndTime())
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "上传中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        CommonUtils.hideLoadingDialog(instances);
                        UtilsLog.e("MyUploadService---getDataUploadVideo==onSuccess==" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                        String result = response.body();
                        UtilsLog.e("MyUploadService---上传视频-result==" + result);
                        String logStr = "\n" + "MyUploadService---外检上传视频--请求成功" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("MyUploadService---上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                UtilsLog.e("MyUploadService---上传视频-成功==");
                                carsInforModel.setStatement("1");
                                carsInforModel.save();
                            }
                        } else {
                            UtilsLog.e("MyUploadService---上传视频-result==" + "没有数据");
                        }
                        upload_times = 0;
                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);
                        String str = "MyUploadService---totalSize:" + progress.totalSize +
                                "currentSize:" + progress.currentSize +
                                "date:" + progress.date +
                                "fraction:" + String.valueOf(progress.fraction) +
                                "exception:" + progress.exception;
                        UtilsLog.e("上传视频==uploadProgress====" + str);
                        UtilsLog.e("上传视频==uploadProgress====" + (progress.fraction * 100) + "%");
                        String logStr = "\n" + "上传视频==uploadProgress====" +
                                "\n" + "uploadProgress::" + str + "\n"
                                + "Progress::" + progress.toString();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        carsInforModel.setProgress(progress.fraction);
                        carsInforModel.save();
//                        EventBus.getDefault().post(carsInforModel);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UtilsLog.e("MyUploadService---getDataUploadVideo==onError==" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
//                        UpVideo_ok = false;
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.body());
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.getException());
                        String logStr = "\n" + "MyUploadService---上传录像视频-onError-失败" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        upload_times++;
                        if (upload_times < 3) {
                            String logStr12 = "\n" + "MyUploadService---上传录像视频-" +
                                    upload_times + "次上传==" + "\n";
                            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr12.getBytes());
                            getDataUploadVideo(carsInforModel, true, currentOutputVideoPath);
                        }
//                        CommonUtils.hideLoadingDialog(instances);
//                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }
    //上传视频 is:是否压缩  true  是   false 否
    private void getDataUploadVideo2(final VideoUploadModel carsInforModel,String filePath, String currentOutputVideoPath) {
        String video_url_path = "";
        if (!TextUtils.isEmpty(currentOutputVideoPath)) {
            video_url_path = currentOutputVideoPath;
        } else {
            video_url_path = filePath;
        }
        UtilsLog.e("MyUploadService---getDataUploadVideo==start==" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
        UtilsLog.e("MyUploadService---上传视频---currentOutputVideoPath==" + currentOutputVideoPath);
        UtilsLog.e("MyUploadService---上传视频---carsInforModel==" + carsInforModel.toString());
        UtilsLog.e("MyUploadService---上传视频---url==" + carsInforModel.getPath());
        String logStrqw = "\n" + "MyUploadService---外检上传视频--getDataUploadVideo--" +
                "\n" + "currentOutputVideoPath::" + currentOutputVideoPath + "\n"
                + "carsInforModel:" + carsInforModel.toString() + "\n"
                + "url:" + carsInforModel.getPath() + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
        OkGo.<String>post(carsInforModel.getPath())
//                .isMultipart(true)
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", carsInforModel.getVideoType())
                .params("ItemCode", carsInforModel.getItemCode())
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getCarNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", carsInforModel.getLine())
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", new File(video_url_path))
                //开始时间
                .params("StartTime", carsInforModel.getStartTime())
                //结束时间
                .params("EndTime", carsInforModel.getEndTime())
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "上传中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        CommonUtils.hideLoadingDialog(instances);
                        UtilsLog.e("MyUploadService---getDataUploadVideo==onSuccess==" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                        String result = response.body();
                        UtilsLog.e("MyUploadService---上传视频-result==" + result);
                        String logStr = "\n" + "MyUploadService---外检上传视频--请求成功" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("MyUploadService---上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                UtilsLog.e("MyUploadService---上传视频-成功==");
                                carsInforModel.setStatement("1");
                                carsInforModel.save();
                            }
                        } else {
                            UtilsLog.e("MyUploadService---上传视频-result==" + "没有数据");
                        }
                        upload_times = 0;
                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);
                        String str = "MyUploadService---totalSize:" + progress.totalSize +
                                "currentSize:" + progress.currentSize +
                                "date:" + progress.date +
                                "fraction:" + String.valueOf(progress.fraction) +
                                "exception:" + progress.exception;
                        UtilsLog.e("上传视频==uploadProgress====" + str);
                        UtilsLog.e("上传视频==uploadProgress====" + (progress.fraction * 100) + "%");
                        String logStr = "\n" + "上传视频==uploadProgress====" +
                                "\n" + "uploadProgress::" + str + "\n"
                                + "Progress::" + progress.toString();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        carsInforModel.setProgress(progress.fraction);
                        carsInforModel.save();
//                        EventBus.getDefault().post(carsInforModel);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UtilsLog.e("MyUploadService---getDataUploadVideo==onError==" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
//                        UpVideo_ok = false;
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.body());
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.getException());
                        String logStr = "\n" + "MyUploadService---上传录像视频-onError-失败" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        upload_times++;
                        if (upload_times < 3) {
                            String logStr12 = "\n" + "MyUploadService---上传录像视频-" +
                                    upload_times + "次上传==" + "\n";
                            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr12.getBytes());
                            getDataUploadVideo(carsInforModel, true, currentOutputVideoPath);
                        }
//                        CommonUtils.hideLoadingDialog(instances);
//                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }
//
//    private void initFile() {
//        makeRootDirectory(PATH);
//        currentOutputVideoPath = PATH + GetPathFromUri.getVideoFileName();
//        //压缩后的视频地址
//        UtilsLog.e("MyUploadService---压缩后的视频地址===" + currentOutputVideoPath);
//    }
//
//    private void initVideo() {
//        //真正的视频压缩初始化
//        mCompressor = new Compressor(this);
//        mCompressor.loadBinary(new InitListener() {
//            @Override
//            public void onLoadSuccess() {
//                UtilsLog.e("MyUploadService---视频压缩初始化---load library succeed");
//            }
//
//            @Override
//            public void onLoadFail(String reason) {
//                UtilsLog.e("MyUploadService---视频压缩初始化---load library fail:" + reason);
//            }
//        });
//    }


//    /**
//     * 视频压缩开始
//     */
//    private void startCompress(final VideoUploadModel model) {
//        String mVideoPath = model.getSize();
//        getVideoTime(mVideoPath);
//        try {
//            if (TextUtils.isEmpty(mVideoPath)) {
//                Toast.makeText(this, "请重新选择视频", Toast.LENGTH_SHORT).show();
////                finish();
//            } else {
//                File file = new File(currentOutputVideoPath);
//                if (file.exists()) {
//                    file.delete();
//                }
//                String cmd = "";
//                UtilsLog.e("MyUploadService---startCompress=mVideoPath=" + mVideoPath);
//                if (videoGotation == 90 || videoGotation == 270) {//之前以为和旋转的角度有关系，原来
//                    UtilsLog.e("MyUploadService---videoGotation=90");
//                    cmd = "-y -i " + mVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " +
//                            "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 480x800 -aspect 9:16 " + currentOutputVideoPath;
//                } else {
//                    UtilsLog.e("videoGotation=0");
//                    if (videoWidth > videoHeight) {
//                        cmd = "-y -i " + mVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " +
//                                "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 800x480 -aspect 16:9 " + currentOutputVideoPath;
//                    } else {
//                        cmd = "-y -i " + mVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " +
//                                "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 480x800 -aspect 9:16 " + currentOutputVideoPath;
//                    }
//                }
//                String str = "MyUploadService---压缩开始--Compressing..." + "\n"
//                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
//                        + "\n" + model.toString() + "startCompress=mVideoPath=" + mVideoPath + "\n" +
//                        "currentOutputVideoPath==" + currentOutputVideoPath + "\n";
//                UtilsLog.e("MyUploadService---onStart==" + str);
//                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
//                startTime = System.currentTimeMillis();
//                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
//                execCommand(cmd, model);
//            }
//        } catch (Exception e) {
//            UtilsLog.e("MyUploadService---startCompress=e=" + e.getMessage());
//            String str = "MyUploadService---startCompress=e=..." + "\n" + e.getMessage() + "\n";
//            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
//        }
//    }

//    private void execCommand(final String cmd, final VideoUploadModel model) {
//        File mFile = new File(currentOutputVideoPath);
//        if (mFile.exists()) {
//            mFile.delete();
//        }
//        UtilsLog.e("cmd= " + cmd);
//        mCompressor.execCommand(cmd, new CompressListener() {
//            @Override
//            public void onExecSuccess(String message) {
////                success input:/storage/emulated/0/myvideo/1648691854535.mp4,size:19.732645MB,
////                        output:/storage/emulated/0/apeng/android_2022040710454381251.mp4,size:3.8561773MB
////                if (mProcessingDialog!=null){
////                    mProcessingDialog.dismiss();
////                }
//                UtilsLog.e("MyUploadService---压缩--success ---model.getSize()---" + model.getSize());
//                String result = getString(R.string.compress_result_input_output, model.getSize()
//                        , getFileSize(model.getSize()), currentOutputVideoPath, getFileSize(currentOutputVideoPath));
//                UtilsLog.e("MyUploadService---压缩--success " + result);
//                UtilsLog.e("MyUploadService---压缩--success--currentOutputVideoPath--- " + currentOutputVideoPath);
//                getDataUploadVideo(model, true, currentOutputVideoPath);
////                Toast.makeText(context, "success " + result, Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onExecFail(String reason) {
//                UtilsLog.e("MyUploadService---onExecFail--fail--压缩失败--- " + reason);
//                String str = "MyUploadService---压缩--onExecFail--fail--压缩失败---" + "\n" + reason + "\n";
//                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
////                Toast.makeText(context, "压缩失败", Toast.LENGTH_SHORT);
////                if (mProcessingDialog!=null){
////                    mProcessingDialog.dismiss();
////                }
////                finish();
//            }
//
//            @Override
//            public void onExecProgress(String message) {
//                try {
//                    String str = "MyUploadService---压缩--onExecProgress--message--" + "\n" + message + "\n";
//                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
//                    UtilsLog.e("MyUploadService---progress " + message);
//
//                    double switchNum = getProgress(message);
//                    if (switchNum == 10000) {
//                        //如果找不到压缩的片段，返回为10000
//                        String str2 = "MyUploadService---如果找不到压缩的片段，返回为10000--switchNum---" + "\n" + switchNum + "\n";
//                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str2.getBytes());
//                        UtilsLog.e("MyUploadService---10000");
////                        if (mProcessingDialog!=null){
////                            mProcessingDialog.setProgress(0);
////                        }
//                    } else {
//                        UtilsLog.e("MyUploadService---progress ===" + (int) (getProgress(message) / 10));
////                        if (mProcessingDialog!=null){
////                            mProcessingDialog.setProgress((int) (getProgress(message) / 10));
////                        }
//                    }
//                } catch (Exception e) {
////                    if (mProcessingDialog!=null){
////                        mProcessingDialog.dismiss();
////                    }
//                    String str = "MyUploadService---onExecProgress--压缩失败---" + "\n" + e.getMessage() + "\n";
//                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, str.getBytes());
//                    UtilsLog.e("MyUploadService---onExecProgress--e=" + e.getMessage());
//                }
//            }
//        });
//    }

    /**
     * 获取视频的时长
     */
    void getVideoTime(String mVideoPath) {
        try {
            MediaMetadataRetriever retr = new MediaMetadataRetriever();
            retr.setDataSource(mVideoPath);
            videoTime = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);//获取视频时长
            videoWidth = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));//获取视频的宽度
            videoHeight = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));//获取视频的高度
            videoGotation = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));//获取视频的角度

            UtilsLog.e("MyUploadService---videoWidth=" + videoWidth);
            UtilsLog.e("MyUploadService---videoHeight=" + videoHeight);

//            MyLog.i(TAG, "videoTime=" + videoTime);
//            mBitMap = retr.getFrameAtTime();
            videoLength = Double.parseDouble(videoTime) / 1000.00;
            UtilsLog.e("MyUploadService---videoLength=" + videoLength);

        } catch (Exception e) {
            e.printStackTrace();
            UtilsLog.e("MyUploadService---异常错误==e=" + e.getMessage());
            videoLength = 0.00;
//            finish();
//            Toast.makeText(this, "异常错误", Toast.LENGTH_SHORT);
        }

    }

    /**
     * 没有文件夹。创建文件夹
     *
     * @param filePath
     */
    public void makeRootDirectory(String filePath) {
        UtilsLog.e("MyUploadService---makeRootDirectory=");
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                Boolean isTrue = file.mkdir();
                UtilsLog.e("MyUploadService---istrue=" + isTrue + "");
            }
        } catch (Exception e) {

        }
    }

    /**
     * 进度条，只能是整形，所以max为1000，最少为0
     *
     * @param source
     * @return
     */
    double getProgressNum = 0.0;

    private double getProgress(String source) {
        if (source.contains("too large")) {//当文件过大的时候，会会出现 Past duration x.y too large
            UtilsLog.e("MyUploadService---too large");
            return getProgressNum;
        }
        Pattern p = Pattern.compile("00:\\d{2}:\\d{2}");
        Matcher m = p.matcher(source);
        if (m.find()) {
            //00:00:00
            String result = m.group(0);
            String temp[] = result.split(":");
            double seconds = Double.parseDouble(temp[1]) * 60 + Double.parseDouble(temp[2]);
            if (0 != videoLength) {
                getProgressNum = seconds / videoLength * 1000;
                return seconds / videoLength * 1000;
            }
            if (seconds == videoLength) {
                return 1000;
            }
        }
//        MyLog.i(TAG, "!m.find()="+getProgressNum);
        return 10000;//出现异常的时候，返回为10000
//      return 0;//出现异常的时候，显示上一个进度条
    }

    private String getFileSize(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return "0 MB";
        } else {
            long size = f.length();
            return (size / 1024f) / 1024f + "MB";
        }
    }
}
